﻿using Nirvana;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 富文本：可以实现聊天，公告等带图片的文本内容和颜色字体
/// </summary>
[RequireComponent(typeof(RichTextGroup))]
public class UIImageRichText : MonoBehaviour
{
    RichTextGroup richTextGroup;
    [SerializeField]
    private Text textPrefab;

    [Header("输入结束后，复制粘贴刷新下")]
    [SerializeField]
    [TextArea]
    private string m_text;
    public string text
    {
        get { return m_text; }
        set { m_text = value; ParseText(m_text); }
    }
    // Start is called before the first frame update
    void Awake()
    {
        richTextGroup = GetComponent<RichTextGroup>();
        richTextGroup.SetTextPrefab(textPrefab);
        richTextGroup.Clear();
    }

#if UNITY_EDITOR

    private void OnValidate()
    {
        if (richTextGroup == null) richTextGroup = GetComponent<RichTextGroup>();
        richTextGroup.SetTextPrefab(textPrefab);
        richTextGroup.Clear();
        if (!string.IsNullOrEmpty(m_text)) ParseText(m_text);
    }

#endif


    private void OnDestroy()
    {
        richTextGroup.SetTextPrefab(null);
        textPrefab = null;
        richTextGroup = null;
        m_text = null;
    }

    /// <summary>
    /// 解析富文本，查看是否有图片码协议
    /// </summary>
    public void ParseText(string text)
    {
        AddText(text);
        AddNewLine();
    }
    public void Clear()
    {
        if (richTextGroup != null) richTextGroup.Clear();
    }
    public void AddText(string text)
    {
        if (richTextGroup != null) richTextGroup.AddText(text);
    }

    public void AddImage(GameObject obj)
    {
        if (richTextGroup != null) richTextGroup.AddObject(obj);
    }
    public void AddNewLine()
    {
        if (richTextGroup != null) richTextGroup.AddNewLine();
    }
}
